package com.wswy.wzcx.ui.dmv;

import android.graphics.Rect;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import com.che.libcommon.utils.optional.function.Supplier;

public class PopupContainer {

  private PopupWindow mPopupWindow;

  private ContentViewSupplier mViewProvider;

  public PopupContainer(ContentViewSupplier viewProvider) {
    this.mViewProvider = viewProvider;
  }

  private int anchorY;
  private int maxHeight = LayoutParams.WRAP_CONTENT;
  private PopupWindow.OnDismissListener mOnDismissListener;

  public void setMaxHeight(int maxHeight) {
    this.maxHeight = maxHeight;
  }

  public void show(View anchor) {
    disMissPopupWindow();
    if(mPopupWindow != null){
      mPopupWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, 0, anchorY);
      return;
    }


    FrameLayout frameLayout = new FrameLayout(anchor.getContext());


    final View contentLayout = mViewProvider.getView(frameLayout);
    if (contentLayout.getParent() instanceof ViewGroup) {
      ((ViewGroup) contentLayout.getParent()).removeView(contentLayout);
    }


    frameLayout.setBackgroundColor(0x30000000);
    frameLayout.addView(contentLayout, ViewGroup.LayoutParams.MATCH_PARENT, maxHeight);
    frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

    View rootView = anchor.getRootView();
    Rect rect = new Rect();
    rootView.getWindowVisibleDisplayFrame(rect);

    int[] xy = new int[2];
    anchor.getLocationInWindow(xy);
    anchorY = xy[1] + anchor.getHeight();

    int height = rect.bottom - anchorY; //计算MATCH_PARENT的实际高度

    mPopupWindow = new PopupWindow(frameLayout, ViewGroup.LayoutParams.MATCH_PARENT, height);
    mPopupWindow.setOutsideTouchable(true);
    mPopupWindow.setFocusable(true);
    mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        if (event.getY() > contentLayout.getBottom()) {
          disMissPopupWindow();
          return true;
        }
        return false;
      }
    });


    mPopupWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, 0, anchorY);

    if (mOnDismissListener != null) {
      mPopupWindow.setOnDismissListener(mOnDismissListener);
    }
  }

  public void disMissPopupWindow() {
    if (mPopupWindow != null && mPopupWindow.isShowing()) {
      mPopupWindow.dismiss();
    }
  }



  public void setOnDismissListener(PopupWindow.OnDismissListener onDismissListener) {
    mOnDismissListener = onDismissListener;
  }




  public interface ContentViewSupplier{
    View getView(ViewGroup container);
  }
}
